//
//  ZLHomeViewModel.swift
//  新浪微博
//
//  Created by 朱玉龙 on 9/27/16.
//  Copyright © 2016 朱玉龙. All rights reserved.
//
// https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.00IHMzYG7vY_6B7f6fbd6f7etuYCQB
import UIKit
import YYModel
class ZLHomeViewModel: NSObject {

    lazy var homeViewArray = [ZLStatusViewModel]()
    
    
    
    func loadData(pullUp: Bool, finished:@escaping (Bool,Int) -> ()) {
        
        let token = ZLOAthorViewModel.shareOAthor.account?.access_token ?? ""
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        var paramters = ["access_token" :token]
//        上拉刷新
        if pullUp == true {
            let last = homeViewArray.last
            paramters["max_id"] = "\((last?.status?.id ?? 0)  - 1)"
        } else {
            //下拉刷新
            let first = homeViewArray.first
            paramters["since_id"] = "\(first?.status?.id ?? 0)"
            
        }
        
        
        ZLNetworkingTools.sharedTools.loadData(method: .GET, urlString: urlString, parameters: paramters) { (reponseObject, error) in
            
            if error != nil {
                
                print(error)
                
                finished(false,0)
                
                return
            }
            
            let dict = reponseObject as! [String : Any]
            
            guard let array = dict["statuses"] as? [[String : Any]] else {
                
                finished(false,0)
                
                return
            }
            
            var tempArray: [ZLStatusViewModel]? = [ZLStatusViewModel]()
            
            for item in array {
                
                let statusViewMoel = ZLStatusViewModel()
                
                let s = ZLStatus()
                
                s.yy_modelSet(with: item)
                
                statusViewMoel.status = s
                
                tempArray?.append(statusViewMoel)
                
            }
            let acount = tempArray?.count

            if pullUp == false  {
                
                self.homeViewArray = tempArray! + self.homeViewArray
                
            } else if pullUp == true {
                
                self.homeViewArray += tempArray!
            }
  
            finished(true,acount ?? 0)
        }
        
        
    }
    
    
    
}
